package com.ki.glasscase.svc.dao.impl;

import com.ki.glasscase.svc.dao.ProductTagDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Logger;

/**
 * Created by Khacheresyants.L on 2/18/14.
 */
@Repository
public class ImplProductTagDAO implements ProductTagDAO {
    private Logger logger = Logger.getLogger("ImplProductDAO.class");

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public boolean create(final Long productId, final Long tagId) {
        String sqlQuery = "INSERT INTO product_tags (tag_id, product_id) VALUES (?,?);";
        if (tagId == 0 || productId == 0) {
            return false;
        }
        try {
            jdbcTemplate.update(sqlQuery, new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement) throws SQLException {
                    preparedStatement.setLong(1, tagId);
                    preparedStatement.setLong(2, productId);
                }
            });
        } catch (DuplicateKeyException dpk) {
            logger.info("Duplicate key tag_id= " + tagId + " product_id=" + productId);
            return false;
        }
        return true;
    }

}
